<?php
namespace app\common\controller;

class Apicommon extends Common
{
    public $uid = '';
    public function initialize()
    {
        parent::initialize();
        $action = $this->request->action();
        if($action == 'index'){
            $token = input('server.HTTP_TOKEN');
            $count = db('member_user')->where(['jwt_token'=>$token])->count();
            if ($count <= 0){
                echo json_encode(array('code'=>401,'msg'=>'请登录'));die;
            }
            $checkuser = JWT::decode($token,config('jwt')['key'],array('HS256'));
            if ($checkuser == false || $checkuser == 120 || $checkuser == 110) {
                $this->uid = 0;
            }else{
                $userinfo = json_decode($checkuser,true);
                $this->uid = $userinfo['id'];;
            }
        }
    }
    protected function ajaxReturn($code,$msg,$array2=array()){
        $array1 = array('code'=>$code,'msg'=>$msg);
        $data = array_merge($array1,$array2);
//        @RedisServer::unlock($this->uid);
//        dump($res);die;
        return json($data);
    }

    /**
     * 返回操作成功,JSON格式数据
     * @param string $msg
     * @param array $data
     */
    protected function success_json($msg = '', $data = [])
    {
        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
            'timestamp' => time(),
        ];
        // @RedisServer::unlock($this->uid);
        $response = \think\Response::create($result, 'json')->header([]);
        throw new \think\exception\HttpResponseException($response);
    }

    /**
     * 返回操作失败,JSON格式数据
     * @param string $msg
     * @param array $data
     */
    protected function error_json($msg = '', $data = [])
    {
        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data,
            'timestamp' => time(),
        ];
        // @RedisServer::unlock($this->uid);
        $response = \think\Response::create($result, 'json')->header([]);
        throw new \think\exception\HttpResponseException($response);
    }
}